// internal/config/config.go
package config

import "github.com/spf13/viper"

type Config struct {
	Server ServerConfig `mapstructure:"server"`
	Redis  RedisConfig  `mapstructure:"redis"`
	Game   GameConfig   `mapstructure:"game"`
	Log    LogConfig    `mapstructure:"log"`
}

type ServerConfig struct {
	Host          string `mapstructure:"host"`
	Port          int    `mapstructure:"port"`
	WebSocketPath string `mapstructure:"websocket_path"`
}

type RedisConfig struct {
	Addr     string `mapstructure:"addr"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}

// 卡牌游戏基础配置
type GameConfig struct {
	MaxPlayersPerRoom   int  `mapstructure:"max_players_per_room"`
	StartingHandSize    int  `mapstructure:"starting_hand_size"`
	MaxDeckSize         int  `mapstructure:"max_deck_size"`
	TurnDurationSeconds int  `mapstructure:"turn_duration_seconds"`
	EnableRuleEngine    bool `mapstructure:"enable_rule_engine"`
	AllowSpectators     bool `mapstructure:"allow_spectators"`
}

// 日志配置
type LogConfig struct {
	Level        string `mapstructure:"level"`    // debug|info|warn|error
	Encoding     string `mapstructure:"encoding"` // json|console
	EnableCaller bool   `mapstructure:"enable_caller"`
}

func Load() (*Config, error) {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./configs")

	// 默认值，确保基础配置即使缺失也有合理行为
	viper.SetDefault("server.host", "0.0.0.0")
	viper.SetDefault("server.port", 8080)
	viper.SetDefault("server.websocket_path", "/ws")

	viper.SetDefault("redis.addr", "127.0.0.1:6379")
	viper.SetDefault("redis.password", "")
	viper.SetDefault("redis.db", 0)

	viper.SetDefault("game.max_players_per_room", 4)
	viper.SetDefault("game.starting_hand_size", 5)
	viper.SetDefault("game.max_deck_size", 30)
	viper.SetDefault("game.turn_duration_seconds", 30)
	viper.SetDefault("game.enable_rule_engine", true)
	viper.SetDefault("game.allow_spectators", false)

	viper.SetDefault("log.level", "info")
	viper.SetDefault("log.encoding", "json")
	viper.SetDefault("log.enable_caller", true)

	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}

	var config Config
	if err := viper.Unmarshal(&config); err != nil {
		return nil, err
	}

	return &config, nil
}
